<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="118px">
      <el-form-item label="课程名字" prop="cname">
        <el-input
          v-model="queryParams.cname"
          placeholder="请输入课程名字"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学校—专业" prop="mid">
        <select-course ref="selectCourse" :mID="queryParams.mid" :placeholder="queryParams.sid?'请选择专业':'请先选择学校'"
                       @selectChange="selectChange"
        ></select-course>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['curriculumSystemManagement:course:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['curriculumSystemManagement:course:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['curriculumSystemManagement:course:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['curriculumSystemManagement:course:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="课程名字" align="center" prop="cname"></el-table-column>
      <el-table-column label="所属专业" align="center">
        <template slot-scope="scope">
          {{scope.row.major.mname}}
        </template>
      </el-table-column>
      <el-table-column label="所属学校" align="center">
        <template slot-scope="scope">
          {{scope.row.school.sname}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['curriculumSystemManagement:course:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['curriculumSystemManagement:course:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @opened="opened" @close="close">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="课程名字" prop="cname">
          <el-input v-model="form.cname" placeholder="请输入课程名字"/>
        </el-form-item>
        <el-form-item label="学校—专业" prop="mid">
            <select-course ref="selectCourseForm" column :mID="form.mid" :placeholder="form.sid?'请选择专业':'请先选择学校'"
                         @selectChange="formSelectChange"
          ></select-course>
        </el-form-item>
        <el-divider content-position="center">教材</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" :disabled="hncjTextbookList.length>=1" @click="handleAddHncjTextbook">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteHncjTextbook">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="hncjTextbookList" :row-class-name="rowHncjTextbookIndex"
                  @selection-change="handleHncjTextbookSelectionChange" ref="hncjTextbook"
        >
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="教材名称">
            <template slot-scope="scope">
              <select-book ref="selectBook" :key="scope.$index" :code="scope.row.code" @selectChange="selectBookChange($event,scope.$index)"></select-book>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="btnLoading" :disabled="btnLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCourse,
  getCourse,
  delCourse,
  addCourse,
  updateCourse,
  exportCourse, course_bookAdd
} from '@/api/curriculumSystemManagement/course'
import selectSchool from '@/views/curriculumSystemManagement/components/selectSchool'
import selectCourse from '@/views/curriculumSystemManagement/components/selectCourse'
import SelectBook from '@/views/curriculumSystemManagement/components/selectBooks'

export default {
  name: 'Course',
  components: {
    SelectBook,
    selectSchool,
    selectCourse
  },
  data() {
    return {
      btnLoading:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedHncjTextbook: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程管理表格数据
      courseList: [],
      // ${subTable.functionName}表格数据
      hncjTextbookList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cname: null,
        mid: null,
        sid: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cname:[
          {required:true,message:"课程名字不能为空",trigger:"blur"}
        ],
        mid:[
          {required:true,message:"专业不能为空",trigger:"change"}
        ]
      },
      //已选择的学校id
      sID: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 窗口关闭的回调*/
    close(){
      this.$refs.selectCourseForm.courseTotal = 10
      this.$refs.selectCourseForm.courseList = []
    },
    /** 窗口打开的回调*/
    opened(){
      if(this.form.id){
        if(this.form.mid){
          this.$refs.selectCourseForm.courseId = this.form.mid
        }
        if(this.form.sid){
          this.$refs.selectCourseForm.$refs.selectSchool.schoolId = this.form.sid
          this.$refs.selectCourseForm.queryParames.sid = this.form.sid
        }
      }else{
        this.$refs.selectCourseForm.courseId = null
        this.$refs.selectCourseForm.$refs.selectSchool.schoolId = null
        this.$refs.selectCourseForm.queryParames.sid = null
      }
      this.$refs.selectCourseForm.getCourseList()
      console.log(this.form.codes)
      if(this.form.codes!=null){
        this.$refs.selectBook.getAllBookList()
      }
    },
    /** 弹窗里的选择专业*/
    formSelectChange(e){
      if (typeof e.sid === 'string') {
        e.sid = null
      }
      if (typeof e.mid === 'string') {
        e.mid = null
      }
      this.form.mid = e.mid
      this.form.sid = e.sid
    },
    /** 选择教材*/
    selectBookChange(e,index){
      this.hncjTextbookList[index].code = e
      this.form.bid = e
    },
    /** 选择专业*/
    selectChange(e) {
      if (typeof e.sid === 'string') {
        e.sid = null
      }
      if (typeof e.mid === 'string') {
        e.mid = null
      }
      this.queryParams.mid = e.mid
      this.queryParams.sid = e.sid
    },
    /** 查询课程管理列表 */
    getList() {
      this.loading = true
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        cname: null,
        mid: null,
        sid:null,
        bid:null,
        codes:null
      }
      this.hncjTextbookList = []
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.$refs.selectCourse.courseId = null
      this.$refs.selectCourse.resetQuerySchool()
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {
        id:null,
        cname:'',
        sid:null,
        mid:null
      }
      this.hncjTextbookList = []
      this.open = true
      this.title = '添加课程管理'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '修改课程管理'
      this.form = {}
      this.form = {
        id:row.id,
        cname:row.cname,
        sid:row.school.id,
        mid:row.mid,
        codes:row.codes
      }
      let codes = row.codes!=null?row.codes.split(","):[]
      let list = []
      for (let i in codes){
        let item = {
          code:codes[i]
        }
        list.push(item)
      }
      this.hncjTextbookList = list
      this.open = true
    },
    /** 提交按钮 */
    submitForm() {
      const self = this
      this.$refs['form'].validate(async valid => {
        if (valid) {
          this.form.hncjTextbookList = this.hncjTextbookList
          let tempcodes = []
          for (let i in this.form.hncjTextbookList){
            tempcodes.push(this.form.hncjTextbookList[i].code)
          }
          this.form.codes = tempcodes.join(",")
          console.log(this.form)
          if (this.form.id != null) {
            self.btnLoading = true
            updateCourse(this.form).then(response => {
              self.btnLoading = false
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).catch(()=>{
              self.btnLoading = false
            })
          } else {
            self.btnLoading = true
            addCourse(this.form).then(response => {
              self.btnLoading = false
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).catch(()=>{
              self.btnLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除"' + row.cname + '"的数据项？').then(function() {
        return delCourse(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** ${subTable.functionName}序号 */
    rowHncjTextbookIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** ${subTable.functionName}添加按钮操作 */
    handleAddHncjTextbook() {
      let obj = {}
      obj.code = ''
      this.hncjTextbookList.push(obj)
    },
    /** ${subTable.functionName}删除按钮操作 */
    handleDeleteHncjTextbook() {
      if (this.checkedHncjTextbook.length == 0) {
        this.$modal.msgError('请先选择要删除的教材数据')
      } else {
        const hncjTextbookList = this.hncjTextbookList
        const checkedHncjTextbook = this.checkedHncjTextbook
        this.hncjTextbookList = hncjTextbookList.filter(function(item) {
          return checkedHncjTextbook.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleHncjTextbookSelectionChange(selection) {
      this.checkedHncjTextbook = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal.confirm('是否确认导出所有课程管理数据项？').then(() => {
        this.exportLoading = true
        return exportCourse(queryParams)
      }).then(response => {
        this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    }
  }
}
</script>
